<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>复合视图</title>
</head>
<body>
    <h1>复合视图</h1>
    <h2>同一段内存之中的多个视图</h2>

    <script>
        // 创建一个复合视图
        const buffer = new ArrayBuffer(24);

        // 创建不同的视图
        const idView = new Uint32Array(buffer, 0, 1);  // 4字节
        const heightView = new Float32Array(buffer, 4, 1);  // 4字节
        const widthView = new Float32Array(buffer, 8, 1);   // 4字节
        const flagsView = new Uint8Array(buffer, 12, 4);    // 4字节
        const matrixView = new Float32Array(buffer, 16, 2); // 8字节

        // 写入数据
        idView[0] = 42;
        heightView[0] = 1.8;
        widthView[0] = 2.5;
        flagsView.set([1, 0, 1, 0]);
        matrixView.set([1.1, 2.2]);

        // 实际应用示例
        // 1. 游戏对象数据结构
        class GameObject {
            constructor() {
                this.buffer = new ArrayBuffer(16);
                this.position = new Float32Array(this.buffer, 0, 2);  // x, y
                this.rotation = new Float32Array(this.buffer, 8, 1);  // angle
                this.flags = new Uint8Array(this.buffer, 12, 4);      // 状态标志
            }

            setPosition(x, y) {
                this.position[0] = x;
                this.position[1] = y;
            }

            setRotation(angle) {
                this.rotation[0] = angle;
            }

            setFlag(index, value) {
                this.flags[index] = value ? 1 : 0;
            }
        }

        // 2. 网络协议数据包
        class DataPacket {
            constructor() {
                this.buffer = new ArrayBuffer(20);
                this.header = new Uint16Array(this.buffer, 0, 2);   // 包头
                this.type = new Uint8Array(this.buffer, 4, 1);      // 包类型
                this.length = new Uint32Array(this.buffer, 5, 1);   // 数据长度
                this.payload = new Uint8Array(this.buffer, 9, 11);  // 数据负载
            }

            setHeader(value1, value2) {
                this.header[0] = value1;
                this.header[1] = value2;
            }

            setType(type) {
                this.type[0] = type;
            }

            setPayload(data) {
                this.length[0] = data.length;
                this.payload.set(data);
            }
        }

        // 使用示例
        const gameObj = new GameObject();
        gameObj.setPosition(100, 200);
        gameObj.setRotation(45);
        gameObj.setFlag(0, true);

        const packet = new DataPacket();
        packet.setHeader(0xFFFF, 0x0000);
        packet.setType(1);
        packet.setPayload(new Uint8Array([1, 2, 3, 4, 5]));
    </script>
</body>
</html>  